﻿using System.Collections.Generic;
using System.Net;
using System.Text;
using FairyGUI;
using UnityEngine;
using UnityEngine.Networking;
using ZFramework.Runtime;
using ZFramework.Runtime.WebRequest;

namespace ZGame
{
    public class UIFormLogicLogin : FGuiUIFormLogicBase
    {
        public override string UIPackageName => "Loading";

        public override string UIComponentName => "Login";

        private GButton _btnLogin;
        private GComboBox _comboBoxServerList;

        private List<string> _serverNames;
        private List<string> _serverGateUrls;
        private int _selectedIndex;

        private int _reqServerListRequestId;
        private int _loginRequestId;
        
        public override void OnInit(object userData)
        {
            base.OnInit(userData);
            _serverNames = new List<string>();
            _serverGateUrls = new List<string>();
            _btnLogin = UI.GetChild("_btnLogin").asButton;
            _btnLogin.onClick.Add(() =>
            {
                if (_selectedIndex < 0)
                    return;
                Log.Error("aaaaaa");
                LoginByGuestParams param = new LoginByGuestParams();
                param.uid = "9c6c820b859b19f8a84d454b550f4d755fc8fa9d";
                param.device_language = "cn";
                param.device = "H410M S2 V2 (Gigabyte Technology Co., Ltd.";
                param.no_encrypt = true;
                param.pkg_version = "3.0.1705388933";
                param.device_memory = "16301";
                param.device_id = "9c6c820b859b19f8a84d454b550f4d755fc8fa9d";
                param.pkg_name = "com.allstarunion.demonwithin";
                param.version = "3.0.1705388933";
                param.server_id = "s205";
                param.device_os = "WindowsEditor";
                string json = JsonUtility.ToJson(param);
                byte[] body = Encoding.UTF8.GetBytes(json);
                _loginRequestId = AOTGameEntry.webRequestManager.AddWebRequest("http://172.16.10.57:3000/auth/loginbyguest", body, 0, "application/json;charset=utf-8");
                Log.Error($"_loginRequestId=={_loginRequestId}");
            });
            _comboBoxServerList = UI.GetChild("_comboBox").asComboBox;
        }

        public override void OnOpen(object userData)
        {
            base.OnOpen(userData);
            AOTGameEntry.eventMgr.Subscribe(WebRequestSuccessEventArgs.EventId, OnWebRequestSuccess);
            _selectedIndex = -1;
            _reqServerListRequestId = -1;
            _loginRequestId = -1;
            var param = new RequstServerListParams();
            param.platform = 1000;
            param.uid = "c6c820b859b19f8a84d454b550f4d755fc8fa9d";
            param.version = "3.0.1705388933";
            
            string json = JsonUtility.ToJson(param);
            
            byte[] body = Encoding.UTF8.GetBytes(json);
            _reqServerListRequestId = AOTGameEntry.webRequestManager.AddWebRequest("http://172.16.10.57:3000/auth/servers", body, 0, "application/json;charset=utf-8");
            Log.Error($"_reqServerListRequestId=={_reqServerListRequestId}");
        }

        public override void OnClose(object userData)
        {
            base.OnClose(userData);
            AOTGameEntry.eventMgr.Unsubscribe(WebRequestSuccessEventArgs.EventId, OnWebRequestSuccess);
        }

        private void OnWebRequestSuccess(object sender, GameEventArgs args)
        {
            var e = args as WebRequestSuccessEventArgs;
            if (e == null)
                return;
            var serialId = e.SerialId;
            if (serialId == _reqServerListRequestId)
            {
                OnRequstServerListCallback(e);
            }else if (serialId == _loginRequestId)
            {
                OnLogin(e);
            }
        }

        private void OnRequstServerListCallback(WebRequestSuccessEventArgs e)
        {
            string data = Utility.Converter.GetString(e.GetWebResponseBytes());
            var serversInfo = JsonUtility.FromJson<ServersInfo>(data);
            Log.Error($"e=={e.SerialId}, serverInfo=={data}");
            _serverNames.Clear();
            _serverGateUrls.Clear();
            _selectedIndex = 0;
            var lastId = serversInfo.serverId;
            for(int i = 0; i < serversInfo.servers.Length; i++)
            {
                var serverInfo = serversInfo.servers[i];
                if (lastId != string.Empty && serverInfo.uuid == lastId)
                {
                    _selectedIndex = i;
                }
                _serverNames.Add(serverInfo.name);
                _serverGateUrls.Add(serverInfo.gate_url);
            }

            if (_selectedIndex >= 0)
            {
                _comboBoxServerList.items = _serverNames.ToArray();
                _comboBoxServerList.values = _serverGateUrls.ToArray();
                _comboBoxServerList.selectedIndex = _selectedIndex;
            }
        }

        private void OnLogin(WebRequestSuccessEventArgs e)
        {
            string data = Utility.Converter.GetString(e.GetWebResponseBytes());
            Log.Error($"登录成功, data=={data}");
            var loginSuccessParams = JsonUtility.FromJson<LoginSuccessParams>(data);
            var IPs = Dns.GetHostAddresses(loginSuccessParams.connectHost);
            var ipAdreess = IPs[0];
            GameEntry.netMessageMgr.Connect(ipAdreess, int.Parse(loginSuccessParams.port));
        }
    }
}